package com.xxg.renrenorder.config;

import com.xxg.renrencommon.domain.filedenum.ReturnCodeEnum;
import com.xxg.renrencommon.domain.result.BaseResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 通用参数校验异常处理
 *
 * @author xxg
 * @date 2020-09-25
 */
@RestControllerAdvice
public class CommonExceptionHandler {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder("参数错误:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            stringBuilder.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";");
        }
        String msg = stringBuilder.toString();
        return new BaseResult(ReturnCodeEnum.INVALID_PARAMETER, msg, null);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResult handleConstraintViolationException(ConstraintViolationException ex) {
        return new BaseResult(ReturnCodeEnum.INVALID_PARAMETER, ex.getMessage(), null);
    }
}
